/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosl.norg.general.gui;

import com.nanosl.lib.db.Manager;
import com.nanosl.norg.ent.Code;
import com.nanosl.norg.util.NTopComponent;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.table.DefaultTableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
    dtd = "-//com.nanosl.credit.editor//CodeEditor//EN",
autostore = false)
@TopComponent.Description(
    preferredID = "CodeEditorTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.nanosl.credit.editor.CodeEditorTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
    displayName = "#CTL_CodeEditorAction",
preferredID = "CodeEditorTopComponent")
@Messages({
    "CTL_CodeEditorAction=CodeEditor",
    "CTL_CodeEditorTopComponent=CodeEditor Window",
    "HINT_CodeEditorTopComponent=This is a CodeEditor window"
})
public final class CodeEditorTopComponent extends NTopComponent {

    Manager mananger = Manager.getInstance();
    DefaultTableModel codeTableModel = new DefaultTableModel();

    public CodeEditorTopComponent() {
        initComponents();
        setName(Bundle.CTL_CodeEditorTopComponent());
        setToolTipText(Bundle.HINT_CodeEditorTopComponent());
        codeTableModel = (DefaultTableModel) codeTable.getModel();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        typeTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        codeTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        codeTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.jLabel1.text")); // NOI18N

        typeTextField2.setText(org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.typeTextField.text")); // NOI18N
        typeTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeTextFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.jLabel2.text")); // NOI18N

        codeTextField.setText(org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.codeTextField.text")); // NOI18N
        codeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                codeTextFieldActionPerformed(evt);
            }
        });

        codeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Type", "Code"
            }
        ));
        codeTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                codeTableKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(codeTable);
        if (codeTable.getColumnModel().getColumnCount() > 0) {
            codeTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.codeTable.columnModel.title0")); // NOI18N
            codeTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.codeTable.columnModel.title1")); // NOI18N
        }

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton2, org.openide.util.NbBundle.getMessage(CodeEditorTopComponent.class, "CodeEditorTopComponent.jButton2.text")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(typeTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(codeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2});

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {codeTextField, typeTextField2});

        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(typeTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(codeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton2});

        jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {codeTextField, typeTextField2});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        resetFields();

    }//GEN-LAST:event_jButton1ActionPerformed

    private void codeTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codeTableKeyPressed
        if (evt.getKeyCode()==127) {
            Code code= (Code) codeTable.getValueAt(codeTable.getSelectedRow(),0);
            if(confirm("Are you sure to delete " + code+"?")){
                manager.delete(Code.class,String.valueOf(code.getCodeInt()));
                fillCodeTable();
            }
        }
    }//GEN-LAST:event_codeTableKeyPressed

    private void codeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_codeTextFieldActionPerformed

        String type = typeTextField.getText().trim();
        String codeText = codeTextField.getText().trim();
        Code code = new Code(type);
        try {
            int codeInt = Integer.parseInt(codeText);
            code.setCodeInt(codeInt);
        } catch (NumberFormatException numberFormatException) {
            code.setCodeVarchar(codeText);
        }
        mananger.update(code);
        fillCodeTable();
        resetFields();

    }//GEN-LAST:event_codeTextFieldActionPerformed

    private void typeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeTextFieldActionPerformed

        String type = typeTextField.getText().trim();
        Code code = mananger.find(Code.class, type);
        if (code != null) {
            String codeText = code.getCodeVarchar();
            if (codeText == null) {
                codeText = code.getCodeInt() != null ? code.getCodeInt() + "" : "";
            }
            codeTextField.setText(codeText);
        }
        codeTextField.requestFocus();

    }//GEN-LAST:event_typeTextFieldActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable codeTable;
    private javax.swing.JTextField codeTextField;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField typeTextField;
    private javax.swing.JTextField typeTextField1;
    private javax.swing.JTextField typeTextField2;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        typeTextField.requestFocus();
        fillCodeTable();
        resetFields();
        
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    private void fillCodeTable() {
        codeTableModel.setRowCount(0);
        Collection<Code> codeCollection = mananger.find(Code.class);
        for (Iterator<Code> it = codeCollection.iterator(); it.hasNext();) {
            Code code = it.next();

            Object[] row = {
                code.getType(),
                code.getCodeInt() != null ? code.getCodeInt() : code.getCodeVarchar(),};
            codeTableModel.addRow(row);
        }
    }

    private void resetFields() {
        codeTextField.setText("");
        typeTextField.setText("");
        typeTextField.requestFocus();
    }
}
